<?php
namespace app\api\controller;

use app\comm\lib\Rest;
use think\Exception;

/**
 * @title 文件上传返回id(将文件大小名称等保存到数据库)
 * @description 接口说明
 * @group 微信报名分销
 * 
 * @param name:file或者file[] type:int require:1 default:1 other: desc:需要上传的文件
 */
class UploadFile extends Rest
{

    protected $_noAuthorization = ['create', 'gets'];
    /**
     * @title 文件上传案例
     * @description 接口说明：请直接访问这个链接
     * @author hardy
     * @url /api/UploadFile
     * @method get
     */
    public function gets(){
        $id = input('get.id');
        if ($id){
            $model = model('UploadFile');
            $data = $model->getOne($id);
            $this->responseSuccess($data);
        } else {
            return $this->view->fetch('gets');
        }
    }
    /**
     * @title 文件上传（返回路径信息）
     * @description 接口说明
     * @author hardy
     * @url /api/UploadFile
     * @method post
     * @return id:int 上传文件的id，提交该id即可
     * @return file:string 相对路径
     */
    public function create(){
        try{
            $p = new \app\extra\ExtraUpload();
            $file = $p->uploadDetail('file');
            if ($file === false){
                throw new Exception('请上传文件');
            }
            if (count($file) == count($file, 1)) {
                $data = [
                    'title' => $file['name'],
                    'file' => $file['filePath'],
                    'url' => $_SERVER['REQUEST_SCHEME'].'://'.env('DOMAIN_NAME').$file['filePath'],
                    'size' => $file['size'],
                    'cate' => $file['cate'],
                    'type' => $file['type'],
                    'upload_date' => time(),
                ];
                $id = model('UploadFile')->insertGetId($data);
                if($id ===false){
                    throw new Exception(model('UploadFile')->getError());
                }
                $data = model('UploadFile')->where('id', $id)->find();
                $this->returnMessage($data);
            } else {
                $ids = [];
                foreach ($file as $item){
                    $data = [
                        'title' => $item['name'],
                        'file' => $item['filePath'],
                        'url' => $_SERVER['REQUEST_SCHEME'].'://'.env('DOMAIN_NAME').$file['filePath'],
                        'size' => $item['size'],
                        'cate' => $item['cate'],
                        'type' => $item['type'],
                        'upload_date' => time(),
                    ];
                    $id = model('UploadFile')->insertGetId($data);
                    if($id ===false){
                        throw new Exception(model('UploadFile')->getError());
                    }
                    $ids[] = $id;
                }
                if (empty($ids)){
                    $this->returnMessage([]);
                }
                $data = model('UploadFile')->where(['id'=>$ids])->select();
                $this->returnMessage($data);
            }
            $this->returnMessage([], false, '请上传文件');
        } catch (\Exception $e){
            $this->returnMessage([], false, $e->getMessage());
        }
    }
    private function returnMessage($data, $status=true, $message='success'){
        $arr = [
            'status' => $status,
            'message' => $message,
            'data'=> $data,
        ];
        header('Content-Type: application/json; charset=UTF-8');
        exit(json_encode($arr));
    }
}